package cloud.maque.admin.impl;

import cloud.maque.admin.domain.entity.MqXzq;
import cloud.maque.admin.domain.request.MqXzqQueryRequest;
import cloud.maque.admin.domain.response.MqXzqTree;
import cloud.maque.admin.mapper.MqXzqMapper;
import cloud.maque.framework.common.request.PaginateDataResquest;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Component
public class MqXzqServiceImplHelper extends ServiceImpl<MqXzqMapper, MqXzq> {


    @Autowired
    private StringRedisTemplate redisTemplate;

    public String GetReidsKey(String parentcode, String isnew, Boolean getchild, String haveself) {
        //Redis缓存
        String rediskey = "maque:xzq:" + parentcode;

        if (!StrUtil.isEmptyIfStr(isnew) && isnew.equals("1")) {
            rediskey = rediskey + ":isnew";
        }

        if (!StrUtil.isEmptyIfStr(getchild) && getchild) {
            rediskey = rediskey + ":all";
        }

        if (!StrUtil.isEmptyIfStr(haveself) && haveself.equals("1")) {
            rediskey = rediskey + ":haveself";
        }

        return rediskey;
    }

    /**
     * 从Redis中获取
     *
     * @return
     */
    public List<MqXzqTree> GetTreeRedis(String parentcode, String isnew, Boolean getchild, String haveself, Boolean fromredis, String outRedisKey) {


        if (fromredis) {
            Object objXzq = redisTemplate.opsForValue().get(outRedisKey);

            if (objXzq != null) {
                List<MqXzqTree> tree = JSON.parseArray(objXzq.toString(), MqXzqTree.class);
                return tree;
            } else {
                return null;
            }
        }

        return null;

    }

    public void SaveTreeRedis(String redisKey, List<MqXzqTree> trees) {

        if (trees != null) {
            String jsonss = JSON.toJSONString(trees);
            redisTemplate.opsForValue().set(redisKey, jsonss);
        }

    }

    /**
     * 把自身插入到队列中
     *
     * @param xzqCode
     * @param trees
     * @return
     */
    public List<MqXzqTree> InsertSel(String xzqCode, List<MqXzqTree> trees) {


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("xzq_code", xzqCode);
        MqXzq xzq = this.getOne(queryWrapper, false);

        if (xzq != null) {
            MqXzqTree xzqTree = new MqXzqTree();
            BeanUtil.copyProperties(xzq, xzqTree);
            List<MqXzqTree> treess = new ArrayList<>();
            xzqTree.setChildren(trees);
            treess.add(xzqTree);
            return treess;

        }
        return trees;
    }

    public QueryWrapper GetQuery(PaginateDataResquest<MqXzqQueryRequest> queryRequest) {
        QueryWrapper<MqXzq> queryWrapper = new QueryWrapper<>();
        if (queryRequest.getData() != null) {

            MqXzqQueryRequest xzq = queryRequest.getData();
            if (!StrUtil.isEmptyIfStr(xzq.getParentXzqCode()) && !xzq.getParentXzqCode().equals("0")) {
                queryWrapper.eq("parent_xzq_code", queryRequest.getData().getParentXzqCode());
            }

            if (!StrUtil.isEmptyIfStr(xzq.getCityScale())) {
                queryWrapper.eq("city_scale", xzq.getCityScale());
            }

            if (!StrUtil.isEmptyIfStr(xzq.getXzqName())) {
                queryWrapper.and(tj -> tj.like("xzq_code", xzq.getXzqName()).or().like("xzq_name", xzq.getXzqName()));
            }
            if (xzq.getMaxLevel() != null && xzq.getMaxLevel() > 1) {
                queryWrapper.eq("length(xzq_code)", xzq.getMaxLevel());
            }

            if (!StrUtil.isEmptyIfStr(xzq.getDisabled())) {
                queryWrapper.lambda().eq(MqXzq::getDisabled, xzq.getDisabled());
            }
            if (!StrUtil.isEmptyIfStr(xzq.getIsNew())) {
                queryWrapper.lambda().eq(MqXzq::getIsNew, xzq.getIsNew());
            }
        }

        queryWrapper.orderByAsc("xzq_code");

        return queryWrapper;
    }

    public Boolean ClearCache() {

        Set<String> keys = redisTemplate.keys("maque:xzq:*");
        redisTemplate.delete(keys);

        Set<String> key2s = redisTemplate.keys("maque:xzqarea:*");
        redisTemplate.delete(key2s);

        return true;
    }

    /**
     * 查询子行政区
     *
     * @return
     */
    public void FillChild(MqXzqTree xzq, List<MqXzq> AllXzqTrees) {

        List<MqXzqTree> subTrees = GetChildFromAllData(xzq.getXzqCode(), AllXzqTrees);
        if (subTrees != null && subTrees.size() > 0) {
            xzq.setChildren(subTrees);
            for (MqXzqTree subXzq : subTrees) {
                this.FillChild(subXzq, AllXzqTrees);
            }
        } else {
            xzq.setChildren(null);
        }

    }

    private List<MqXzqTree> GetChildFromAllData(String xzqCode, List<MqXzq> trees) {

        List<MqXzq> finds = trees.stream().filter(new Predicate<MqXzq>() {
            @Override
            public boolean test(MqXzq MqXzqTree) {
                return MqXzqTree.getParentXzqCode().trim().equals(xzqCode.trim());
            }
        }).collect(Collectors.toList());


        return finds.stream().map(s -> {
            MqXzqTree t = new MqXzqTree();
            BeanUtils.copyProperties(s, t);
            return t;
        }).collect(Collectors.toList());

    }
}
